﻿using ProjectScheduling.daos;
using ProjectScheduling.models;
using System.Data;

namespace ProjectScheduling
{
    public partial class RestDayPage : UserControl
    {
        public static readonly RestDayPage b = new();
        internal List<RestDay> data_list = [];
        public RestDayPage()
        {
            InitializeComponent();
            DataList();
            AddRestDayForm.b.save = DataList;
        }
        private void DataList()
        {
            var years = RestDayDao.Base.Years();
            txt_years.DataSource = years;
            if (years.Count == 0)
            {
                txt_years.Text = string.Empty;
            }
            var year = int.TryParse(txt_years.Text, out int y) ? y : 0;
            view_data.Rows.Clear();

            (data_list = [.. RestDayDao.Base.FindAll(it => year == 0 || it.Day.Year == year).OrderBy(it => it.Day)]).ForEach(item =>
            {
                view_data.Rows.Add(item.Id, item.Day.ToString("yyyy-MM-dd"), item.IsRest, item.Disc, item.CreateTime);
            });

        }
        /// <summary>
        /// 新增按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_add_Click(object sender, EventArgs e)
        {
            
            AddRestDayForm.b.InitData(new RestDay());
            AddRestDayForm.b.ShowDialog();
        }

        private void View_data_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;
            // 编辑按钮
            if (e.ColumnIndex == 5)
            {
                AddRestDayForm.b.InitData(data_list[e.RowIndex]);
                AddRestDayForm.b.ShowDialog();
            }
            // 编辑按钮
            if (e.ColumnIndex == 6)
            {
                if (MessageBox.Show("是否要确定删除", "删除确认", MessageBoxButtons.OKCancel,MessageBoxIcon.Question) == DialogResult.OK)
                {
                    var id = view_data.Rows[e.RowIndex].Cells[0].Value.ToString() ?? "0";
                    RestDayDao.Base.Delete(int.Parse(id));
                    DataList();
                }
            }
        }

        private void View_data_SelectionChanged(object sender, EventArgs e)
        {
            view_data.ClearSelection();
        }
    }
}
